/**
 * 渠道运营－中介机构-已审核
 */
define(function (require, exports, module) {
    var util = require('util');
    var ui = require('ui');
    var $ = require("jquery");
    var angular = require("angular");
    require("angular-ui");
    require("angular-interceptor");
    var api_prefix = G_CONFIG.api_prefix + "qmyx/agency/";
    var api_prefix_broker = G_CONFIG.api_prefix + "qmyx/broker/";

    angular.module('Review', ['ngUI'])
        .service('brokerInfo', ['$q', '$http', function ($q, $http) {
            return function (id) {
                var deferred = $q.defer();
                $http.get(api_prefix_broker + 'get-broker-info-by-id&id=' + id)
                    .success(function (res) {
                        if (res.retCode == 0) {
                            deferred.resolve(res.data);
                        }
                    });
                return deferred.promise;
            }
        }])
        .controller('ReviewController', ['$rootScope', '$scope', '$http','brokerInfo',
            function ($rootScope, $scope, $http,brokerInfo) {

                function doGetData(params) {
                    $scope.loading = true;
                    $http
                        .get(api_prefix + "get-agency-list", {params: params})
                        .then(function (res) {
                            $scope.loading = false;
                            var retCode = res.data.retCode;
                            if (retCode == 0) {
                                var data = res.data.data;
                                $scope.list = data.items;
                                $scope.total = data.total;
                            } else {
                                ui.showErrTip(res.data.errMsg);
                                return false;
                            }
                        })
                        .finally(function () {
                            $scope.loading = false;
                        });
                };
                $scope.searchStatus = '0';
                //获取已审核中介机构列表
                var getData = function () {
                    var params = {
                        curPage: $scope.pageIndex,
                        shenhe: $scope.filter.shenhe.join(","),
                        isdisabled: $scope.filter.isdisabled.join(","),
                        regStart: $scope.filter.startDate,
                        regEnd: $scope.filter.endDate,
                        pageSize: $scope.filter.pageSize
                    };
                    doGetData(params);
                };

                $scope.getData = getData;

                //1搜索获取，按关键字
                function searchByKeyword() {
                    var params = {
                        curPage: $scope.pageIndex,
                        shenhe: '1,2',
                        pageSize: $scope.filter.pageSize
                    };
                    params[$scope.search.queryKey] = $scope.search.keyword;
                    doGetData(params);
                }

                $scope.getSearchData = function () {
                    $scope.pageIndex = 1;
                    $scope.searchStatus = '1';
                    searchByKeyword();
                };

                //2查询已审核中介机构列表
                $scope.getFilterData = function () {
                    $scope.pageIndex = 1;
                    $scope.searchStatus = '0';

                    getData();
                };

                //3分页
                $scope.getDataPage = function (pageIndex) {
                    $scope.pageIndex = pageIndex;

                    if ($scope.searchStatus == 0) {
                        getData();
                    } else {
                        searchByKeyword();
                    }
                };
                //搜索
                $scope.search = {
                    queryKey: "agencyName", keyword: "",
                    fieldList: [
                        {value: 'agencyName', text: '机构公司名称'},
                        {value: 'personInCharge', text: '负责人姓名'},
                        {value: 'mobileTel', text: '负责人电话'}
                    ]
                };

                //查询审核条件
                $scope.reviewShenheList = [
                    {Text: '已通过', selected: false, shenhe: "1"},
                    {Text: '未通过', selected: false, shenhe: "2"}
                ];
                //审核状态选择
                $scope.updataReviewPassCheck = function () {
                    var reviewList = $scope.reviewShenheList;
                    //审核选择
                    var filterShenhe = [];
                    for (var i = 0, item; item = reviewList[i]; i++) {
                        if (item.selected) {
                            filterShenhe.push(item.shenhe);
                        }
                    }

                    if (filterShenhe.length == 0) {
                        filterShenhe = ['1', '2'];
                    }
                    $scope.filter.shenhe = filterShenhe;
                };

                $scope.disabledProxy = {
                    disableTrue:false,
                    disableFalse:false
                };

                $scope.updateDisabledCheck = function () {
                    $scope.filter.isdisabled = [];
                    if($scope.disabledProxy.disableTrue){
                        $scope.filter.isdisabled.push(1);
                    }
                    if($scope.disabledProxy.disableFalse){
                        $scope.filter.isdisabled.push(0);
                    }
                    if($scope.filter.isdisabled.length == 0){
                        $scope.filter.isdisabled = [0,1];
                    }
                };

                //查询
                $scope.filter = {
                    shenhe: [1, 2],
                    isdisabled: [0,1],
                    startDate:'',
                    endDate:'',
                    pageSize: 10,
                    // 撤销过滤
                    clearFilter: function () {
                        for (var i = 0, item; item = $scope.reviewShenheList[i]; i++) {
                            item.selected = false;
                        }
                        $scope.disabledProxy = {
                            disableTrue:false,
                            disableFalse:false
                        };
                        $scope.filter.shenhe = [1, 2];
                        $scope.filter.isdisabled = [0,1];
                        $scope.filter.startDate = '';
                        $scope.filter.endDate = '';
                        $scope.getFilterData();
                    }
                };

                //中介机构审核通过
                $scope.passReview = function (item) {
                    util.confirm('确定审核通过吗？', {
                        ok: function () {
                            $http
                                .post(api_prefix + "audit-pass", {token: util.getToken(), agencyId: item.b_agenciesId})
                                .success(function (res) {
                                    var retCode = res.retCode;
                                    if (retCode == 0) {
                                        item.shenhe_status = "已通过";
                                        ui.showSucTip();
                                    } else {
                                        ui.showErrTip(res.errMsg);
                                    }
                                })
                        }
                    })
                };

                //禁用
                $scope.setDisable = function (item) {
                    util.confirm('确定禁用吗？', {
                        ok: function () {
                            $http
                                .post(api_prefix + "disable", {token: util.getToken(), agencyId: item.b_agenciesId})
                                .success(function (res) {
                                    var retCode = res.retCode;
                                    if (retCode == 0) {
                                        ui.showSucTip();
                                        item.isdisabled = "已禁用";

                                    } else {
                                        ui.showErrTip(res.errMsg);
                                    }
                                })
                        }
                    })
                };

                //启用
                $scope.setEnable = function (item) {
                    util.confirm('确定启用吗？', {
                        ok: function () {
                            $http
                                .post(api_prefix + "enable", {token: util.getToken(), agencyId: item.b_agenciesId})
                                .success(function (res) {
                                    var retCode = res.retCode;
                                    if (retCode == 0) {
                                        ui.showSucTip();
                                        item.isdisabled = "未禁用";
                                    } else {
                                        ui.showErrTip(res.errMsg);
                                    }
                                })
                        }
                    })
                };


                $scope.getAgentData = function (item, dialog, $dialogScope) {
                    dialog.button([]);
                    //经济人审核通过
                    function brokerPassReview(params) {
                        util.confirm('确定审核通过吗？', {
                            ok: function () {
                                $http
                                    .post(api_prefix_broker + "audit-pass", {brokerIds: params })
                                    .success(function (res) {
                                        var retCode = res.retCode;
                                        if (retCode == 0) {
                                            getBrokerData($dialogScope.pageIndex);
                                            ui.showSucTip();
                                        } else {
                                            ui.showErrTip(res.errMsg);
                                        }
                                    })
                            }
                        })
                    }

                    $dialogScope.brokerPassReview = function (item) {
                        brokerPassReview(item.b_regbrokerId);
                    };
                    //批量审核参数
                    function brokerBatchReview() {
                        var b_regbrokerId = [];
                        var data = $dialogScope.data;
                        for (var i = 0, item; item = data[i]; i++) {
                            if (item.selected) {
                                b_regbrokerId.push(item.b_regbrokerId);
                            }
                        }
                        return b_regbrokerId;
                    }

                    //批量经济人审核通过
                    $dialogScope.brokerBatchPassReview = function () {
                        var b_regbrokerId = brokerBatchReview();
                        if (b_regbrokerId.length < 1) {
                            util.alert('请选择要操作的记录！');
                            return;
                        }
                        brokerPassReview(b_regbrokerId.join(","));
                    };
                    //批量经济人审核不通过
                    $dialogScope.brokerBatchUnPassReview = function () {
                        var b_regbrokerId = brokerBatchReview();
                        if (b_regbrokerId.length < 1) {
                            util.alert('请选择要操作的记录！');
                            return;
                        }
                        brokerUnPassReview(b_regbrokerId.join(","));
                    };
                    //经济人审核不通过
                    function brokerUnPassReview(params) {
                        util.confirm('确定审核不通过吗？', {
                            ok: function () {
                                $http
                                    .post(api_prefix_broker + "audit-fail", {brokerIds: params})
                                    .success(function (res) {
                                        var retCode = res.retCode;
                                        if (retCode == 0) {
                                            getBrokerData($dialogScope.pageIndex);
                                            ui.showSucTip();
                                        } else {
                                            ui.showErrTip(res.errMsg);
                                        }
                                    })
                            }
                        })
                    }

                    $dialogScope.brokerUnPassReview = function (item) {
                        brokerUnPassReview(item.b_regbrokerId);
                    };


                    //审核机构经纪人列表取消全选
                    $dialogScope.updateReivewAgentCheckAll = function () {
                        var data = $dialogScope.data;
                        for (var i = 0, item; item = data[i]; i++) {
                            item.selected = $dialogScope.reivewAgentSelectedAll;
                        }
                    }
                    //审核机构经纪人列表同步全选/取消全选
                    $dialogScope.updateReivewAgentCheck = function () {
                        var data = $dialogScope.data;
                        var checked = true;
                        for (var i = 0, item; item = data[i]; i++) {
                            if (!item.selected) {
                                checked = false;
                                break;
                            }
                        }
                        $dialogScope.reivewAgentSelectedAll = checked;
                    };

                    //机构待审核经济人身份搜索
                    $dialogScope.brokerSearch = {
                        keyword: '',
                        queryKey: 'brokerName',
                        pageSize: '10',
                        fieldList: [
                            {value: 'brokerName', text: '经纪人姓名'},
                            {value: 'brokerMobile', text: '经纪人电话'}
                        ]

                    };

                    //获取机构待审核经纪人列表
                    var getBrokerData = function (pageIndex) {
                        pageIndex = pageIndex || 1;
                        var params = {curPage: pageIndex, agencyId: item.b_agenciesId, shenhe: 0};
                        params[$dialogScope.brokerSearch.queryKey] = $dialogScope.brokerSearch.keyword;
                        $dialogScope.loading = true;
                        return $http
                            .get(api_prefix + "get-agency-broker-list", {params: params})
                            .success(function (res) {
                                var retCode = res.retCode;
                                if (retCode == 0) {
                                    $dialogScope.loading = false;
                                    $dialogScope.data = res.data.items;
                                    $dialogScope.total = res.data.total;
                                    $dialogScope.pageIndex = pageIndex;
                                    //$dialogScope.pageSize = $dialogScope.brokerSearch.pageSize;
                                    $dialogScope.$applyAsync();
                                    setTimeout(function () {
                                        dialog.reset();
                                    });
                                } else {
                                    ui.showErrTip(res.errMsg);
                                }
                            })
                    };

                    getBrokerData(1);

                    $dialogScope.getBrokerData = getBrokerData;
                };

                //门店显示配置
                $scope.shopConfig = {
                    pageIndex: 1,
                    pageSize: '10'
                };

                $scope.getShopData = function (item, dialog, $dialogScope) {
                    dialog.button([]);
                    //获取门店列表
                    function doGetShopData(params, $dialogScope, dialog) {
                        $dialogScope.loading = true;
                        $http
                            .get(api_prefix + "get-store-list-pass", {params: params})
                            .success(function (res) {
                                var retCode = res.retCode;
                                if (retCode == 0) {
                                    $dialogScope.loading = false;
                                    $dialogScope.data = res.data.items;
                                    $dialogScope.total = res.data.total;
                                    $dialogScope.$applyAsync();
                                    setTimeout(function () {
                                        dialog.reset();
                                    });
                                } else {
                                    ui.showErrTip(res.errMsg);
                                }
                            });
                    };
                    $dialogScope.pageSize = $scope.shopConfig.pageSize;

                    //获取门店分页列表
                    $dialogScope.getShopDataPage = function (pageIndex) {
                        pageIndex = pageIndex || 1;
                        var params = {
                            agencyId: item.b_agenciesId,
                            curPage: pageIndex,
                            pageSize: $dialogScope.pageSize
                        };
                        $dialogScope.pageIndex = pageIndex;
                        doGetShopData(params, $dialogScope, dialog);
                    };
                    $dialogScope.getShopDataPage();

                };

                $scope.getPassBrokerData = function (item, dialog, $dialogScope) {
                    dialog.button([]);
                    //获取经纪人列表
                    function doGetPassBrokerData(params, $dialogScope, dialog) {
                        params['USE_FORM_DATA'] = false;
                        $dialogScope.loading = true;
                        return $http
                            .post(api_prefix_broker + "query-agency-broker-page-list&pageIndex="+($dialogScope.pageIndex-1)+"&pageSize="+$dialogScope.brokerSearch.pageSize, params)
                            .success(function (res) {
                                var retCode = res.retCode;
                                if (retCode == 0) {
                                    $dialogScope.loading = false;
                                    $dialogScope.data = res.data.items;
                                    $dialogScope.total = res.data.total;
                                    $dialogScope.$applyAsync();
                                    setTimeout(function () {
                                        dialog.reset();
                                    });
                                } else {
                                    ui.showErrTip(res.errMsg);
                                }
                            });
                    };

                    //机构经纪人搜索
                    $dialogScope.brokerSearch = {
                        keyword: '',
                        queryKey: 'broker_name',
                        pageSize: '10',
                        fieldList: [
                            {value: 'broker_name', text: '经纪人姓名'},
                            {value: 'mobile_tel', text: '经纪人电话'}
                        ]

                    };

                    //获取经纪人分页列表
                    $dialogScope.getPassBrokerDataPage = function (pageIndex) {
                        pageIndex = pageIndex || 1;
                        var params = {
                            search_field: $dialogScope.brokerSearch.queryKey,
                            search_text: $dialogScope.brokerSearch.keyword,
                            status_arr: [1],
                            agency_arr: [item.b_agenciesId]
                        };
                        $dialogScope.pageIndex = pageIndex;
                        return doGetPassBrokerData(params, $dialogScope, dialog);
                    };
                    $dialogScope.getPassBrokerDataPage();

                    /* 设置经纪人相关操作 */
                    var $scope = $dialogScope;
                    $scope.onShowBrokerInfo = function (item, dialog, dialogScope) {
                        dialog.button([]);
                        dialogScope.handleBroker = $scope.handleBroker;

                        dialogScope.showPreviewImg = function (src) {
                            var imgpreview;
                            $scope.ImgSize(src, function () {
                                var w = this.width, h = this.height;
                                var maxW = 1100, minW = 250;
                                if (w > maxW) {
                                    w = maxW;
                                    h = maxW / w * h;
                                } else if (w > minW) {
                                    w = minW;
                                    h = minW / w * h;
                                }
                                imgpreview = dialogC({
                                    title: '图片预览',
                                    fixed: true,
                                    content: '<img width="100%" height="100%" src="' + src + '" />',
                                    width: w,
                                    height: h,
                                    okDisplay: false,
                                    cancelDisplay: false
                                }).showModal();
                            });
                        };
                        dialogScope.currentState =
                        {
                            name: '已审定',
                            value: [1],
                            audited: true
                        };
                        dialogScope.setStatus = function (data, status) {
                            $scope.setStatus.apply($scope, arguments).success(function (res) {
                                dialogScope.data.status = status;
                                if (status == 1) {
                                    dialogScope.data.status_info = '已通过';
                                } else if (status == 2) {
                                    dialogScope.data.status_info = '未通过';
                                } else {
                                    dialogScope.data.status_info = '未审核';
                                }
                                dialog.close();
                            })
                        };
                        dialogScope.setInvite = $scope.setInvite;
                        brokerInfo(item.broker_id)
                            .then(function (info) {
                                dialogScope.data = info;
                            })
                            .finally(function () {
                                setTimeout(function () {
                                    dialog.reset();
                                }, 0);
                            })
                    };

                    /**
                     * 重设密码对话框
                     * @param {Object} item
                     * @param dialog
                     * @param dialogScope
                     */
                    $scope.onShowChangePwd = function (item, dialog, dialogScope) {
                        dialogScope.data = item;
                    };
                    /**
                     * 重设密码
                     * @param {Object} data
                     */
                    $scope.changePwd = function (data) {
                        $http.post(api_prefix_broker + 'reset-broker-password&id=' + data.broker_id +
                        '&password1=' + data.password1 + '&password2=' + data.password2)
                            .success(function (res) {
                                if (res.retCode == 0) {
                                    ui.showSucTip();
                                    $scope.getPassBrokerDataPage();
                                }
                            })

                    };
                    /**
                     *启用、禁用、删除
                     */
                    $scope.handleBroker = function (item, opt) {
                        var map = {'disable': 'disable-broker', 'enable': 'enable-broker', 'del': 'delete-broker'};
                        if (opt && _.has(map, opt)) {
                            var method = map[opt];
                        } else {
                            return;
                        }
                        return $http.post(api_prefix_broker + method + '&id=' + item.broker_id)
                            .success(function (res) {
                                if (res.retCode == 0) {
                                    $scope.getPassBrokerDataPage().finally(function () {
                                        ui.showSucTip();
                                        if (opt == 'disable' || opt == 'enable') {
                                            item.isdisabled = !item.isdisabled;
                                        }
                                    });
                                }
                            })
                    };
                    /**
                     *更新经纪人是否允许邀请
                     *
                     */
                    $scope.setInvite = function (item, opt) {
                        var canInvite = true;
                        if (typeof opt !== 'undefined') {
                            canInvite = opt;
                        } else {
                            return;
                        }
                        $http.post(api_prefix_broker + 'update-can-invite-broker&id=' + item.broker_id + '&canInvite=' + canInvite)
                            .success(function (res) {
                                if (res.retCode == 0) {
                                    $scope.getPassBrokerDataPage().finally(function () {
                                        ui.showSucTip();
                                        item.can_invite_broker = !item.can_invite_broker;
                                    });
                                }
                            })
                    };
                };

                //导出已审核机构列表
                $scope.exportData = function (e) {
                    var params = {
                        shenhe: $scope.filter.shenhe.join(","),
                        isdisabled: $scope.filter.isdisabled.join(","),
                        regStart: $scope.filter.startDate,
                        regEnd: $scope.filter.endDate
                    };
                    params[$scope.search.queryKey] = $scope.search.keyword;
                    $(e.target).attr('href', api_prefix + "export&" + $.param(params));
                };

                //获取已审核列表数据
                getData();
            }
        ])
})
;